﻿<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="PageTitle" runat="server">
    <title>日考勤管理</title>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="PageStyles" runat="server">
    <style type="text/css">
        .fieldslist
        {
            word-break: break-all;
            word-wrap: break-word;
        }
        .fieldslist li
        {
            display: block;
        }
        .divInfo
        {
            width: 90px;
        }
        .alink
        {
            width: 50px;
        }
        .expText
        {
            width: 280px;
        }
        .selector
        {
            width: 52px;
        }
        
        #txtRemark
        {
            font-size: 14px;
            width: 450px;
        }
        #txtRemark:hover
        {
            background-color: #FFFFAA;
        }
        #divRemark
        {
            margin-top: 10px;
            border-bottom: 1px solid #ccc;
        }
        .divEdit
        {
            margin-top: 10px;
            display: none;
            border-bottom: 1px solid #ccc;
        }
    </style>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="PageScripts" runat="server">
    <script src="../../Scripts/Attendance/attendance.js" type="text/javascript"></script>
    <script type="text/javascript">
    //************* URL常量
    var URL_MODITY_ATTENDANCE_EVALUATION = "/Attendance/ModifyAttendanceEvaluation";
    var URL_DISAGREE_ATTENDANCE_EVALUATION_APPLICATION = "/Attendance/RejectEvaluationApplication";
    var URL_UPDATE_REMARK = "/Attendance/UpdateRemarkTheday";
    //************* 全局变量
    var g_Var = {
        "time": null,
        "targetUserId": null,
        "dataStorage": null
    };
    //************* 常量定义
    var Service = {};
    function InitService() {
        Service.DoUpdateRemark = $.AsyncMethod(URL_UPDATE_REMARK,"Post");
    }
    var StaticResource = {
        "WeekendInfo": {
            "false": "非周末",
            "true": "周末"
        },
        "IsNeedToWork": {
            "false": "休息",
            "true": "正常上班"
        },
        "YesOrNoBing": [
            {
                "text": "是",
                "value": true
            },
            {
                "text": "否",
                "value": false
            }
        ],
        "ApplicationState": {
            "Applying": "正在处理",
            "Done": "已处理"
        },
        "ItemName": {
            "LateMiniutes": "迟到",
            "EarlyMiniutes": "早退",
            "IsAbsense": "旷工",
            "IsExtraWork": "加班",
            "ManHours": "获得工时"
        },
        "timeTarget": {
            "minute": "分钟",
            "hour": "小时"
        },
        "YesOrNoTarget": {
            "false": "否",
            "true": "是",
            "False": "否",
            "True": "是"
        },


    };


    //************* Accessor访问器
    var EzAccessor = {};
    function CreateAccessor() {
            EzAccessor = CreateRealEzAccessor();
    }


    function CreateRealEzAccessor() {
        //实现服务器交互方法
        var realEzAccessor = {
            "getModifyAttendanceApplication": function () {
                return <%= ViewData["ModifyAttendanceApplication"] %>;
            },

            "getDayInfo": function () {
                return <%= ViewData["DayInfo"] %>;
            },
            "getTargetUser": function () {
                return <%=ViewData["TargetUser"]%>

            },
            "getCurrentDate": function () {

                   return <%=ViewData["CurrentDate"]%>;
            },
            "getDayAttendanceDetail": function () {
                return <%= ViewData["DayAttendanceDetail"] %>;
            },

            "geEvaluationModifyHistory": function () {
                return <%= ViewData["EvaluationModifyHistory"] %>;
            },


            "doModifyAttendanceEvaluation": function (targetUserId, date, lateMiniutes, leaveEarlyMiniutes, isAbsense, isExtraWork, manHours) {
                //HttpPost
                $.post(
                    URL_MODITY_ATTENDANCE_EVALUATION,
                    {
                        'targetUserId': targetUserId,
                        'date': date,
                        'lateMiniutes': lateMiniutes,
                        'leaveEarlyMiniutes': leaveEarlyMiniutes,
                        'isAbsense': isAbsense,
                        'isExtraWork': isExtraWork,
                        'manHours': manHours
                    },
                    function (e) {
                         if (e.Status == "Success") {
                            var url = '/Attendance/ModifyAttendanceInfoPerDay?time={time}&userId={targetUserId}';
                            url = url.replace("{time}", date)
                                     .replace("{targetUserId}", targetUserId);
                            $.redirectAndDisplayInfo(url, e);
                        } else {
                            $.displayStatusInfo(e);
                        }
                    }
                );
                
            },
             "doDisAgreeTheApplication": function(applicationId){
                $(document).ajaxBusy('begin');
                $.post(
                    URL_DISAGREE_ATTENDANCE_EVALUATION_APPLICATION,
                    {'applicationId': applicationId},
                    function (e) {
                        $(document).ajaxBusy('end');
                        $.displayStatusInfo(e);
                        pageReload();
                    }
                );
            }
        };

        return realEzAccessor;
    }


    function bindRemark(remarkInfo){
        var remark = remarkInfo? remarkInfo.Remark : "";
        
        if(remark.htmlEncode().trim() !=  ""){
            $('#txtRemark').html(remark);
        }   
        else {
            $('#txtRemark').html('单击此处添加考勤备注');
        } 
    }

    //上下班打卡考勤记录
    function bindCheckAttendanceDetail(attendanceInfoList) {
        var ondutyNum = 0;
        var offdutyNum = 0;
        for (var key in attendanceInfoList) {
            var actionTime = Date.fromEpoch(attendanceInfoList[key].ActionTime).toFullTimeFormat();
            var isAbnormal = attendanceInfoList[key].IsAbnormalAttendance ? '<span class="important">*</span>' : "";
            var explanation = attendanceInfoList[key].Explanation;
            var explanationStr = (explanation == null)? "" : explanation; 
            var attendanceDom = '<p>{isAbnormal}{actionTime}</p><p class="expText">{Explanation}</p>';
            attendanceDom = attendanceDom.replace("{actionTime}", actionTime)
                                         .replace("{isAbnormal}", isAbnormal)
                                         .replace("{Explanation}", explanationStr);
            //上班
            if (attendanceInfoList[key].AttendanceType == "onDuty") {
                $('#actionTimeOnDuty').append(attendanceDom);
                ondutyNum = ondutyNum + 1
            }
            //下班
            else {
                $('#actionTimeOffDuty').append(attendanceDom);
                offdutyNum = offdutyNum + 1
            }

        }
        //没用考勤记录的处理
        if(ondutyNum == 0){
            $('#actionTimeOnDuty').append('<small>没有考勤记录</small>');     
        }
        if(offdutyNum == 0){
            $('#actionTimeOffDuty').append('<small>没有考勤记录</small>');  
        }

    }


    //假期信息
    function bindLeaveInfoDetail(leaveList) {
        var leaveInfo = leaveList.Leaves;
        if (leaveInfo.length == 0) {
            $('#cmbLeaveInfo').parent().parent().remove();
        }
        for (var key in leaveInfo) {
            var leaveName = leaveInfo[key].LeaveTypeName;
            var startTime = Date.fromEpoch(leaveInfo[key].StartTime);
            var endTime = Date.fromEpoch(leaveInfo[key].EndTime);
            var startTimeFormat = startTime.toFullTimeFormat();
            var endTimeFormat = endTime.toFullTimeFormat();
            var leaveTime = startTimeFormat + " 至 " + endTimeFormat;

            var leaveInfoDom = '<p>{leaveName} {leaveTime}</p>';

            leaveInfoDom = leaveInfoDom.replace("{leaveName}", leaveName)
                                       .replace("{leaveTime}", leaveTime);

            $('#cmbLeaveInfo').append(leaveInfoDom);
        }
    }



    //考勤评估信息
    function bindAttendanceEvaluationDetail(attendanceEvaluation) {
        var lateMiniute = attendanceEvaluation.LateMiniutes;
        var earlyMiniutes = attendanceEvaluation.EarlyMiniutes;
        var isAbsense = attendanceEvaluation.IsAbsense;
        var isExtraWork = attendanceEvaluation.IsExtraWork;
        var manHours = toManHours(attendanceEvaluation.Manhours);

        $('#cmbBeLate .active-input').val(lateMiniute);
        $('#cmbLeaveEarly .active-input').val(earlyMiniutes);
        $('#selAbsent').attr("value",isAbsense); 
        $('#selExtraWork').attr("value",isExtraWork);
        $('#cmbManHours .active-input').val(manHours);
    }




    function bindAttendanceDetail(attendanceDetail) {
        bindCheckAttendanceDetail(attendanceDetail.AttendanceEvaluation.DayAttendanceInfoList);
        bindLeaveInfoDetail(attendanceDetail.AttendanceEvaluation.LeaveInfo);
        bindAttendanceEvaluationDetail(attendanceDetail.AttendanceEvaluation);
        bindRemark(attendanceDetail.RemarkInfo);
    }





    function editEvaluationItemValue(itemName, value) {
        var editedValue = value + StaticResource.timeTarget.minute;
        switch (itemName) {
            case StaticResource.ItemName.ManHours: editedValue = toManHours(value) + StaticResource.timeTarget.hour;
                break;
            case StaticResource.ItemName.IsExtraWork: editedValue = StaticResource.YesOrNoTarget[value];
                break;
            case StaticResource.ItemName.IsAbsense: editedValue = StaticResource.YesOrNoTarget[value];
                break;

        }

        return editedValue;

    }



    //修改记录
    function showEvaluationModifyHistory(evaluationModifyHistory) {
        if(evaluationModifyHistory){
            for (var key in evaluationModifyHistory) {
                var evaluationChange = $('<div class="evaluationChange"></div>');
                var modifyOn = Date.fromEpoch(evaluationModifyHistory[key].ModifyOn);
                var modifyOnFormat = modifyOn.toShortDateTime();
                var operatorName = evaluationModifyHistory[key].Operator.Name;
                //修改人和修改时间
                var modifyTittle = '<p style="margin-top:10px;">{operatorName} 在 {modifyOnFormat}</p>';
                modifyTittle = modifyTittle.replace("{operatorName}", operatorName)
                                           .replace("{modifyOnFormat}", modifyOnFormat);

                //修改内容
                var modifyInfo = '';
                var attendanceEvaluationChangeList = evaluationModifyHistory[key].EvaluationChangeItem;
                
                for (var target in attendanceEvaluationChangeList) {
                    var itemName = StaticResource.ItemName[attendanceEvaluationChangeList[target].ItemName];
                    var oldValue = attendanceEvaluationChangeList[target].OldValue;
                    var newValue = attendanceEvaluationChangeList[target].NewValue;

                    //时间单位是分钟还是小时
                    //加班和旷工项  对true 和 false的处理
                    oldValue = editEvaluationItemValue(itemName, oldValue);
                    newValue = editEvaluationItemValue(itemName, newValue);

                    modifyInfo = modifyInfo + '<p>将 {itemName} {oldValue} 修改为 {newValue}</p>';
                    modifyInfo = modifyInfo.replace("{itemName}", itemName)
                                            .replace("{oldValue}", oldValue)
                                            .replace("{newValue}", newValue);

                }
                
                if (attendanceEvaluationChangeList.length == 0) {
                    modifyInfo = '<p>拒绝了考勤评估修改申请。</p>';
                }
                $(evaluationChange).append(modifyTittle)
                                   .append(modifyInfo);
                $("#cmbEvaluationModifyHistory").append(evaluationChange);
            }
            
            
            EzTipsManager.showTipBox('tipModifyInfo');
            
            $('.evaluationChange:first-child').find('p').css({'color': '#008B00'});
        }
    }



    //申请历史
    function showApplicationList(application) {
        if(application) {
            var applicationId = application.Id;
            var applyUserName = application.ApplyUser.Name;
            var applyOn = Date.fromEpoch(application.ApplyOn);
            var applyOnFormat = applyOn.toShortDateTime();
            var applyText = application.ApplyText;

            var applyInfoDom = '<p><span>{applyUserName} 于 {applyOn} 申请</span></p><p> 申请原因： <span >{applyText}</span> <a id="disAgree" style="font-size:16px; float:right;">拒绝</a></p>';
            applyInfoDom = applyInfoDom.replace("{applyUserName}", applyUserName)
                                        .replace("{applyOn}", applyOnFormat)
                                        .replace("{applyText}", applyText);
            $('#cmbApplyInfo').append(applyInfoDom);
            
            $('#pnlModify').wrapTipBox({
                tipId: '#tip_ApplyInfo'
                }); 

            $('#disAgree').click(function(){
                EzAccessor.doDisAgreeTheApplication(applicationId);  
            });
           
        }else{
            $('#pnlModify').wrapTipBox('unwrapTipBox'); 
        }

    }





    function showDayInfo(dayInfo) {
        var isWeekEnd = StaticResource.WeekendInfo[dayInfo.IsWeekEnd];
        var needToWork = StaticResource.IsNeedToWork[dayInfo.IsNeedToWork];
        var extraShiftInfo = "";
        var holidayInfo = "";

         if(dayInfo.ExtraShiftInfo && dayInfo.HolidayInfo){
            extraShiftInfo = dayInfo.ExtraShiftInfo.Name
            holidayInfo = dayInfo.HolidayInfo.Name;
        }

        var dayInfoDom = '<p>当日信息 : {weekendInfo}  {holidayInfo}  {extraShiftInfo} {needToWork}</p>';
        dayInfoDom = dayInfoDom.replace("{weekendInfo}", isWeekEnd)
                           .replace("{holidayInfo}", holidayInfo)
                           .replace("{extraShiftInfo}", extraShiftInfo)
                           .replace("{needToWork}", needToWork);

        $('#lblDayInfo').append(dayInfoDom);
    }



    function showApplicationTittle(targetUser, dayInfo) {
        var applyUserName = targetUser.Name;
        var nowDay = Date.fromEpoch(dayInfo.Date).toFullChineseDateFormat();
        var tittleStr = applyUserName + " " + nowDay + " " + "考勤情况";

        $('#lblTittle').html(tittleStr);
    }
    
    function showApplicationDetail(application, dayInfo, currentUser, evaluationModifyHistory) {
        showApplicationList(application);
        showDayInfo(dayInfo);
        showApplicationTittle(currentUser, dayInfo);
        showEvaluationModifyHistory(evaluationModifyHistory);
    }

    

    function initPage() {
        InitService();
        EzTipsManager.addTipBox('#tip_Remind', 'tipRemind');
        EzTipsManager.addTipBox('#tip_ModifyInfo', 'tipModifyInfo');
        
        EzTipsManager.showTipBox('tipRemind');
       
        CreateAccessor();
        var application = EzAccessor.getModifyAttendanceApplication();
        var dayInfo = EzAccessor.getDayInfo();
        var targetUser = EzAccessor.getTargetUser();
        var attendanceDetail = EzAccessor.getDayAttendanceDetail();
        var evaluationModifyHistory = EzAccessor.geEvaluationModifyHistory();
        
        $('#selAbsent').comboxBinding(StaticResource.YesOrNoBing, 'text', 'value');
        $('#selExtraWork').comboxBinding(StaticResource.YesOrNoBing, 'text', 'value');
        
        //将原始数据保存
        g_Var["time"] = dayInfo.Date;
        g_Var["targetUserId"] = targetUser.Id;
        g_Var["currentDate"] = EzAccessor.getCurrentDate();
        
        //增添两个跳转链接
        var monthshortBtnStr = '<a href="/attendance/attendanceInfoListPerMonth?time={time}&userId={userId}" class="head">当月考勤管理</a>'; 
        var managershortBtnStr = '<a href="/attendance/attendanceInfoListPerDayManager?time={time}" class="head">当日考勤管理</a>'; 
        monthshortBtnStr =  monthshortBtnStr.replace("{time}", g_Var["time"])
                                            .replace("{userId}", g_Var["targetUserId"]);
        managershortBtnStr = managershortBtnStr.replace("{time}", g_Var["time"]);
        $('#status-bar').append(monthshortBtnStr)
                        .append(managershortBtnStr);
        //显示相关信息
        showApplicationDetail(application,
                              dayInfo,
                              targetUser,
                              evaluationModifyHistory);

        if(g_Var.time <= g_Var.currentDate){
            if(g_Var.time == g_Var.currentDate)
            {
                $('#nextDay').hide();
            }

            //绑定考勤状况
            bindAttendanceDetail(attendanceDetail);
            //EzFormDialog
            $('#pnlModify').formDialog({
                onDataReady: function (event, isOnOK) {
                    if (isOnOK == true) {
                        $('.pnlModifySubmit').show();
                        $('#pnlModify').css({'border-color': "red"});
                    }
                    else {
                        $('.pnlModifySubmit').hide();
                        $('#pnlModify').css({'border-color': "transparent"});
                    }
                }
            });
        }
        else{ 
            $('#tblNoFuture').show();
            $('#nextDay').hide();
            $('#preDay').hide();
            $('#tblAttendanceInfo').hide(); 
        }
    }



    function getIsRemarkEmpty(){
        var isRemarkEmpty = false;
        if($('#txtRemar').html() == "单击此处添加考勤备注"){
            isRemarkEmpty = true;    
        }

        return isRemarkEmpty;
    }

    function initPageEvent() {
        $('#btnCancel').click(function () {
            //$('#pnlModify').css({'border-color': "transparent"});
            $('#pnlModify').formDialog('resetData');        
        });
        
        
        $('.btn-modify').click(function () {
            $('#pnlModify').formDialog('updateData');

            var targetyUserId = g_Var["targetUserId"];
            var date = g_Var["time"];

            var lateMiniutes = $('#cmbBeLate .active-input').val();
            var leaveEarlyMiniutes = $('#cmbLeaveEarly .active-input').val();
            var manHours = toMiniutes($('#cmbManHours .active-input').val());
            var isAbsense = $('#selAbsent').val();
            var isExtraWork = $('#selExtraWork').val();

            EzAccessor.doModifyAttendanceEvaluation(
                                                        targetyUserId,
                                                        date,
                                                        lateMiniutes,
                                                        leaveEarlyMiniutes,
                                                        isAbsense,
                                                        isExtraWork,
                                                        manHours
                                                    );
        });


        $('#preDay').click(function () {
            var currentDate = Date.fromEpoch(g_Var["time"]);

            var perDay = new Date(
                currentDate.getFullYear(),
                currentDate.getMonth(),
                currentDate.getDate() - 1,
                0,
                0,
                0
            ).toEpoch();

            window.location.href = "ModifyAttendanceInfoPerDay?time="
                           + perDay + "&userId=" + g_Var["targetUserId"];

        });

         $('#nextDay').click(function () {
            var currentDate = Date.fromEpoch(g_Var["time"]);

            var nextDay = new Date(
                currentDate.getFullYear(),
                currentDate.getMonth(),
                currentDate.getDate() + 1,
                0,
                0,
                0
            ).toEpoch();

            window.location.href = "ModifyAttendanceInfoPerDay?time="
                           + nextDay  + "&userId=" + g_Var["targetUserId"];
        });



        $('#txtRemark').click(function (){
            $(this).hide();
            $('.divEdit').show();

            if(getIsRemarkEmpty() == false) {
                $('#template').val($('#txtRemark').html().htmlEncode().trim());    
            }
            $('#template').select();
        });

        $('#btnCancelRemark').click(function (){
            $('#template').clearFields();
            $('#txtRemark').show();
            $('.divEdit').hide();
        });

        $('#btnSumbit').click(function (){
            $('#txtRemark').show();
            $('.divEdit').hide();
            //提交
            var remark = $('#template').val().htmlEncode().trim();
            if(remark != "") {
                Service.DoUpdateRemark( function (e) {
                    if(remark == ""){
                        $('#txtRemark').html("单击此处添加考勤备注");
                    }else{
                        $('#txtRemark').html(remark);
                    }
                    $.displayStatusInfo(e);
                }, {userId: g_Var.targetUserId, time: g_Var.time, remark: remark});
            }
        });
    }




    $(function () {
        initPage();
        initPageEvent();
    });
    </script>
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="PageHead" runat="server">
    <%
        Html.RenderPartial("_sayHello"); %>
</asp:Content>
<asp:Content ID="Content5" ContentPlaceHolderID="PageContent" runat="server">
    <div id="page-head" class="page-head">
        <img src="../../Content/icons/attendance_modify.png" style="width: 48px; height: 48px;"
            alt="modify" />
        <span id="lblTittle" class="title"></span>
        <div style="min-height: 20px; margin-top: 5px;">
            <div style="float: left;">
                <a id="preDay">前一天</a>
            </div>
            <div style="float: right;">
                <a id="nextDay">后一天</a>
            </div>
        </div>
    </div>
    <div id="page-body">
        <div id="tblNoFuture" style="display: none;">
            <%Html.RenderPartial("_noFutureDisplayInfo"); %>
        </div>
        <div id="tblAttendanceInfo">
            <div>
                <ul class="fieldslist">
                    <li>
                        <div class="l">
                            上班：
                        </div>
                        <div id="actionTimeOnDuty" class="r">
                        </div>
                    </li>
                    <li>
                        <div class="l">
                            下班：
                        </div>
                        <div id="actionTimeOffDuty" class="r">
                        </div>
                    </li>
                </ul>
                <ul class="fieldslist">
                    <li>
                        <div class="l">
                        </div>
                        <div id="cmbLeaveInfo" class="r">
                        </div>
                    </li>
                </ul>
            </div>
            <div id="divRemark">
                <p id="txtRemark">
                </p>
            </div>
            <div class="divEdit">
                <textarea id="template" cols="40" rows="5" style="margin-bottom: 10px;"></textarea>
                <div style="margin-bottom: 10px;">
                    <div id="btnSumbit">
                        提交</div>
                    <script type="text/javascript">
                        $(function () {
                            $("#btnSumbit").button({
                                icons: {
                                    primary: "ui-icon-circle-arrow-n"
                                },
                                text: true
                            });
                        });
                    </script>
                    &nbsp;或者&nbsp;<a id="btnCancelRemark">取消</a>
                </div>
            </div>
            <div id="pnlModify" class="formBox" style="margin-top: 10px;">
                <ul class="fieldslist">
                    <li>考勤评估记录（点击修改）： <span class="pnlModifySubmit" style="display:none;float: right;margin-right: 30px;">
                        <div id="btn-modify" class="btn-modify" style="width: 80px;">
                            更改</div>
                        <script>
                        $(function () {
                            $(".btn-modify").button({
                                icons: {
                                    primary: "ui-icon-pencil"
                                },
                                text: true
                            });
                        });
                        </script>

                        或者 <a id="btnCancel">恢复原样</a> </span>
                    </li>
                    <li class="active-container">
                        <div class="l">
                            迟到：
                        </div>
                        <div class="r">
                            <div id="cmbBeLate">
                                <input class="active-input" />分钟
                            </div>
                        </div>
                    </li>
                    <li class="active-container">
                        <div class="l">
                            早退：
                        </div>
                        <div class="r">
                            <div id="cmbLeaveEarly">
                                <input class="active-input" />分钟
                            </div>
                        </div>
                    </li>
                    <li class="active-container">
                        <div class="l">
                            工时：
                        </div>
                        <div class="r">
                            <div id="cmbManHours">
                                <input class="active-input" />小时
                            </div>
                        </div>
                    </li>
                    <li class="active-container">
                        <div class="l">
                            旷工：</div>
                        <div class="r">
                            <select id="selAbsent" class="selector">
                            </select></div>
                    </li>
                    <li class="active-container">
                        <div class="l">
                            加班：</div>
                        <div class="r">
                            <select id="selExtraWork" class="selector">
                            </select></div>
                    </li>
                </ul>
            </div>
        </div>
    </div>
</asp:Content>
<asp:Content ID="Content6" ContentPlaceHolderID="PageShortcut" runat="server">
</asp:Content>
<asp:Content ID="Content7" ContentPlaceHolderID="PageFoot" runat="server">
    <div id="tip_Remind" style="display: none;">
        <h1>
            小贴士:</h1>
        <p class="indent">
            你可以修改考勤评估记录。
        </p>
    </div>
    <div id="tip_ModifyInfo" style="display: none;" class="tip-memo">
        <h1>
            考勤评估修改历史:</h1>
        <div id="cmbEvaluationModifyHistory" class="indent">
        </div>
    </div>
    <div id="tip_ApplyInfo" style="display: none;" class="tip-succ">
        <h1>
            考勤评估修改申请 :</h1>
        <div id="cmbApplyInfo" class="indent">
        </div>
    </div>
</asp:Content>
